package com.example.lobby.listener;

import com.example.common.grpc.ServiceInstanceRegistrar;
import com.example.common.listener.AbstractServiceChangeListener;
import com.example.common.constants.ServiceNames;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

/**
 * 服务变更监听器
 * 监听Nacos服务实例的变化，特别是gate-service和game-service的下线事件
 */
@Slf4j
@Component
public class ServiceChangeListener extends AbstractServiceChangeListener {

    public ServiceChangeListener(DiscoveryClient discoveryClient, ServiceInstanceRegistrar serviceInstanceRegistrar) {
        super(discoveryClient,serviceInstanceRegistrar);
    }
    @Override
    protected void handleServiceChange() {
        // 监听所有服务变化，但主要处理gate-service和game-service
        handleServiceChange(ServiceNames.GATE);
        handleServiceChange(ServiceNames.GAME);
    }

    @Override
    protected void onServiceInstanceChange(String serviceName, java.util.List<org.springframework.cloud.client.ServiceInstance> currentInstances, java.util.List<org.springframework.cloud.client.ServiceInstance> lastInstances) {
        // 可以在这里添加gate-service和game-service特定的处理逻辑
        if (ServiceNames.GATE.value().equals(serviceName)) {
            log.info("Gate服务实例变化处理完成");
        } else if (ServiceNames.GAME.value().equals(serviceName)) {
            log.info("Game服务实例变化处理完成");
        }
    }

    /**
     * 获取当前gate-service可用实例数
     */
    public int getCurrentGateInstanceCount() {
        return getCurrentInstanceCount(ServiceNames.GATE);
    }

    /**
     * 检查gate-service是否可用
     */
    public boolean isGateServiceAvailable() {
        return isServiceAvailable(ServiceNames.GATE);
    }

    /**
     * 获取当前game-service可用实例数
     */
    public int getCurrentGameInstanceCount() {
        return getCurrentInstanceCount(ServiceNames.GAME);
    }

    /**
     * 检查game-service是否可用
     */
    public boolean isGameServiceAvailable() {
        return isServiceAvailable(ServiceNames.GAME);
    }
} 